package com.wswy.wzcx.ui.car.result;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.TextView;
import com.blankj.utilcode.util.SizeUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.AdModel;
import com.wswy.wzcx.model.TrafficViolationInfo;
import com.wswy.wzcx.model.home.RPaths;
import com.wswy.wzcx.model.home.RouterUtils;
import com.wswy.wzcx.model.license.UserCarInfo;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.car.fine.QueryResultDetailActivity;
import com.wswy.wzcx.ui.dialog.WarningDialog;
import com.wswy.wzcx.ui.other.ClickUtils;
import com.wswy.wzcx.utils.ImageUtils;
import com.wswy.wzcx.utils.StringUtils;
import com.wswy.wzcx.widget.utils.VerticalCenterSpan;
import java.util.ArrayList;
import java.util.List;

class QueryResultAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnClickListener{

  //private List<TrafficViolationInfo> items = new ArrayList<>();

  private static final int TYPE_RESULT = 1;
  private static final int TYPE_AD = 2;
  private static final int TYPE_HEAD_INFO = 3;

  private static final int TYPE_FINE_TIPS = 4; //罚单缴费 提示

  private List<Object> datas = new ArrayList<>();

  void setItems(List<TrafficViolationInfo> items){
    this.datas.clear();

    boolean hasList = false;

    if(items != null){
      this.datas.addAll(items);
      hasList = true;
    }

    if(hasList){
      //尝试在第一个添加提示
      this.datas.add(new AdModel());
    }
  }

  void setAdModel(AdModel adModel){
    int lastPos = datas.size() - 1;
    Object o = datas.get(lastPos);
    if(o instanceof AdModel){
      datas.set(lastPos,adModel);
      notifyItemChanged(lastPos);
    }
  }

  void setFineInfo(UserCarInfo carInfo,boolean showTips){
    if (carInfo != null){
      if (!this.datas.isEmpty() && datas.get(0) instanceof TagBeanUserCar){
        this.datas.set(0,new TagBeanUserCar(carInfo,showTips));
      }else {
        this.datas.add(0,new TagBeanUserCar(carInfo,showTips));
      }
    }
  }


  @Override
  public
  RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    if(viewType == TYPE_RESULT){

      return new ResultViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout_result,parent,false));
    }else if(viewType == TYPE_AD){
      return new ADViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_result_ad,parent,false));
    }else if (viewType == TYPE_HEAD_INFO){
      return new FineInfoViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout_result_fine_info,parent,false));
    }else if (viewType == TYPE_FINE_TIPS){
      return new FineTipsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_result_fine_tips,parent,false));
    }

    return null;
  }

  @Override
  public int getItemViewType(int position) {
    Object o = datas.get(position);
    if(o instanceof TrafficViolationInfo){
      return TYPE_RESULT;
    }else if(o instanceof AdModel){
      return TYPE_AD;
    } else if (o instanceof TagBeanUserCar){
      return TYPE_HEAD_INFO;
    } else if (o instanceof Integer && ((Integer)o) == TYPE_FINE_TIPS){
      return TYPE_FINE_TIPS;
    }
    return super.getItemViewType(position);
  }

  @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {

    Object obj = datas.get(position);
    viewHolder.itemView.setTag(R.id.item_data,obj);

    if(viewHolder instanceof ResultViewHolder){

      ResultViewHolder holder = ((ResultViewHolder) viewHolder);
      TrafficViolationInfo item = ((TrafficViolationInfo) obj);
      holder.itemView.setOnClickListener(this);

      holder.tvTime.setText(item.fineTime);
      holder.tvAddress.setText(item.fineLocation);
      holder.tvViolationInfo.setText(item.fineDetail);

      SpannableStringBuilder sb =new SpannableStringBuilder();
      SpannableString str=new SpannableString("罚款 ");
      str.setSpan(new VerticalCenterSpan(14f,ContextCompat.getColor(holder.itemView.getContext(),R.color.textColorPrimary_70)),0,str.length(),SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);

      sb.append(str);
      str=new SpannableString(StringUtils.formatMoney(item.fineFee));
      str.setSpan(new ForegroundColorSpan(ContextCompat.getColor(holder.itemView.getContext(),R.color.accentColor3)),0,str.length(),SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);

      sb.append(str);
      //holder.tvFine.setText(item.fineFee + "元");
      holder.tvFine.setText(sb);

      sb =new SpannableStringBuilder();
      str=new SpannableString("扣分 ");
      str.setSpan(new VerticalCenterSpan(14f,ContextCompat.getColor(holder.itemView.getContext(),R.color.textColorPrimary_70)),0,str.length(),SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);

      sb.append(str);
      str=new SpannableString(String.valueOf(item.fineDeductPoints));
      str.setSpan(new ForegroundColorSpan(ContextCompat.getColor(holder.itemView.getContext(),R.color.accentColor3)),0,str.length(),SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);

      sb.append(str);

      holder.tvPoint.setText(sb);

      holder.tvStatueName.setText(item.getStatusNameDesc(holder.itemView.getContext()));
      if (!TextUtils.isEmpty(item.statusName)) {
        switch (item.statusName) {
          case "10":
            holder.tvStatueName.setTextColor(
                ContextCompat.getColor(holder.itemView.getContext(), R.color.colorPrimary));
            break;
          case "20":
            holder.tvStatueName.setTextColor(
                ContextCompat.getColor(holder.itemView.getContext(), R.color.textColorPrimary_40));
            break;
          case "30":
            holder.tvStatueName.setTextColor(
                ContextCompat.getColor(holder.itemView.getContext(), R.color.colorPrimary));
            break;
          case "40":
            holder.tvStatueName.setTextColor(
                ContextCompat.getColor(holder.itemView.getContext(), R.color.colorPrimary));
            break;
          default:
            holder.tvStatueName.setTextColor(
                ContextCompat.getColor(holder.itemView.getContext(), R.color.textColorPrimary_40));
            break;
        }

        if (TextUtils.equals("20",item.statusName)){
          //不支持代办
          holder.tvFineNoDealTips.setVisibility(View.VISIBLE);
        }else {
          holder.tvFineNoDealTips.setVisibility(View.GONE);
        }

      } else {
        holder.tvFineNoDealTips.setVisibility(View.GONE);
        holder.tvStatueName.setTextColor(
            ContextCompat.getColor(holder.itemView.getContext(), R.color.textColorPrimary_40));
      }
    }else if (viewHolder instanceof ADViewHolder){
      AdModel item = ((AdModel) obj);


      ADViewHolder holder = ((ADViewHolder) viewHolder);
      holder.bindData(item);
    }else if (viewHolder instanceof FineInfoViewHolder){
      TagBeanUserCar item = (TagBeanUserCar) obj;
      ((FineInfoViewHolder) viewHolder).setCarFineInfo(item);
    }


    }

  @Override
  public int getItemCount() {
    return datas.size();
  }

  @Override
  public void onClick(View v) {
    Object tag = v.getTag(R.id.item_data);
    if(tag instanceof TrafficViolationInfo){
      Object obj =  datas.get(0);
      UserCarInfo userCarInfo = null;
      if (obj instanceof TagBeanUserCar){
        userCarInfo = ((TagBeanUserCar) obj).userCarInfo;
      }
      QueryResultDetailActivity.Companion.start(v.getContext(), ((TrafficViolationInfo) tag),userCarInfo);
    }

  }


  static class ResultViewHolder extends RecyclerView.ViewHolder {

        TextView tvTime;
        TextView tvAddress;
        TextView tvViolationInfo;
        TextView tvFine;
        TextView tvPoint;
        TextView tvStatueName;
        TextView tvFineNoDealTips;

        ResultViewHolder(View view) {
            super(view);
          tvTime = view.findViewById(R.id.tv_time);
          tvAddress = view.findViewById(R.id.tv_address);
          tvViolationInfo = view.findViewById(R.id.tv_violation_info);
          tvFine = view.findViewById(R.id.tv_fine);
          tvPoint = view.findViewById(R.id.tv_point);
          tvStatueName = view.findViewById(R.id.tv_status_name);
          tvFineNoDealTips = view.findViewById(R.id.tv_fine_no_deal_tips);
        }
    }

  static class ADViewHolder extends RecyclerView.ViewHolder implements OnClickListener {

    SimpleDraweeView imgAD;
    TextView tvGotoFKDJ;

    private AdModel item;

    ADViewHolder(View itemView) {
      super(itemView);
      itemView.setBackgroundResource(R.color.default_background_color);
      imgAD = itemView.findViewById(R.id.img_ad);
      tvGotoFKDJ = itemView.findViewById(R.id.tv_goto_fkdj);
    }


    void bindData(AdModel item){
      this.item = item;
      if(TextUtils.isEmpty(item.imgUrl)){

        imgAD.setVisibility(View.GONE);
      }else {
        imgAD.setVisibility(View.VISIBLE);

        ImageUtils.showImage(imgAD,item.imgUrl);

      }


      LayoutParams layoutParams =itemView.getLayoutParams();
      if(layoutParams instanceof MarginLayoutParams){
        ((MarginLayoutParams) layoutParams).topMargin = SizeUtils.dp2px(8);
        ((MarginLayoutParams) layoutParams).bottomMargin = SizeUtils.dp2px(10);
      }
      tvGotoFKDJ.setOnClickListener(this);
      imgAD.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
      int id = view.getId();
      if(id == R.id.tv_goto_fkdj){
        RouterUtils.start(view.getContext(), RPaths.fkdj);
//        ModuleActivity.startTarget(view.getContext(), FKDJFragment.TAG);
      }else if(id == R.id.img_ad){
        if(!TextUtils.isEmpty(item.linkUrl)){
          StatTools.sendClick(view.getContext(),StatisticsId.ad_wzcxdetail);
          RouterUtils.startTarget(view.getContext(),item.linkTarget,item.linkUrl);

        }
      }

    }
  }


  static class FineInfoViewHolder extends RecyclerView.ViewHolder{

    TextView tvFineCount;
    TextView tvFinePoints;
    TextView tvFineFee;

    View layoutResultTips;

    FineInfoViewHolder(View itemView) {
      super(itemView);
      tvFineCount = itemView.findViewById(R.id.tv_car_fine);
      tvFinePoints = itemView.findViewById(R.id.tv_car_point);
      tvFineFee = itemView.findViewById(R.id.tv_car_fee);
      layoutResultTips = itemView.findViewById(R.id.layout_result_tips);

      layoutResultTips.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          if (!ClickUtils.isFastClick()){

            new WarningDialog(v.getContext(),"因交管系统数据同步存在延时，已缴费的罚单的违章预计在1~7个工作日后会消除。在此过程不影响，年审、过户、进京证等车务办理。").show();
          }

        }
      });

    }


    void setCarFineInfo(TagBeanUserCar beanTag){

      if (beanTag.showTips){
        layoutResultTips.setVisibility(View.VISIBLE);
      }else {
        layoutResultTips.setVisibility(View.GONE);
      }


      int color = ContextCompat.getColor(itemView.getContext(),R.color.textColorPrimary_70);

      SpannableStringBuilder sb = new SpannableStringBuilder();
      SpannableString string = new SpannableString("未处理违章 ");
      string.setSpan(new VerticalCenterSpan(12.0f,color),0,string.length(),SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
      sb.append(string);
      sb.append(String.valueOf(beanTag.userCarInfo.trafficCount));


      tvFineCount.setText(sb);


      sb = new SpannableStringBuilder();

      string = new SpannableString("扣分 ");
      string.setSpan(new VerticalCenterSpan(12.0f,color),0,string.length(),SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
      sb.append(string);
      sb.append(String.valueOf(beanTag.userCarInfo.totalScore));

      tvFinePoints.setText(sb);


      sb = new SpannableStringBuilder();

      string = new SpannableString("罚款 ");
      string.setSpan(new VerticalCenterSpan(12.0f,color),0,string.length(),SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
      sb.append(string);
      sb.append(String.valueOf(beanTag.userCarInfo.totalFee));

      tvFineFee.setText(sb);
    }

  }

  static class FineTipsViewHolder extends RecyclerView.ViewHolder{

    FineTipsViewHolder(@NonNull View itemView) {
      super(itemView);
    }
  }

  static class TagBeanUserCar{
    @NonNull final UserCarInfo userCarInfo;
    @NonNull final boolean showTips;
    TagBeanUserCar(UserCarInfo userCarInfo, boolean showTips) {
      this.userCarInfo = userCarInfo;
      this.showTips = showTips;
    }
  }

}
